<?php
	session_start();
	require_once("MoneyFactory.class.php"); 
	require_once("MoneyOps.class.php");
?>

<html>
	<head>
		<title>Porte Monnaie - itération 1</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	</head>
	<body>
		<?php

		if ( isset($_POST['v1']) && isset($_POST['devise']) ) {

			$valueNote = 0;
			$valuePiece = 0;
			$currency;

			// billets ou pieces
			if ($_POST["type"] === "valueNote") {
				$valueNote = $_POST['v1'];
			} else if ($_POST["type"] === "valuePiece") {
				$valuePiece = $_POST['v1'];
			}

			if ( isset($_POST['add']) ) {
				// ajout dans le porte monnaie
				$currency = $_POST["devise"];
				$moneyToAdd = MoneyFactory::getDefaultFactory()->createMoney($valueNote, $valuePiece, $currency);
				$currentMoney = unserialize($_SESSION["EUR"]);

				if ($currentMoney == null) {
					$_SESSION["EUR"] = serialize($moneyToAdd);
				} else {
					try {
						$newMoney = MoneyOps::add($moneyToAdd, $currentMoney);
						$_SESSION["EUR"] = serialize($newMoney);
					} catch (Exception $e) {
						echo "<p style='color:red'>impossible traiter cette devise, EUR uniquement supporté</p>";
					}
				}
			} else if ( isset($_POST['sub']) ) {
				// suppression dans le porte monnaie
				$currency = $_POST["devise"];
				$moneyToSub = MoneyFactory::getDefaultFactory()->createMoney($valueNote, $valuePiece, $currency);
				$currentMoney = unserialize($_SESSION["EUR"]);

				if ($currentMoney != null) {
					try {
						$newMoney = MoneyOps::sub($currentMoney, $moneyToSub);
						$_SESSION["EUR"] = serialize($newMoney);
					} catch (IncompatiblesCurrenciesException $e) {
						echo "<p style='color:red'>impossible de traiter cette devise, EUR uniquement supporté</p>";
					} catch (InvalidMoneyValueException $e) {
						echo "<p style='color:red'>impossible de supprimer, vous n'avez pas assez d'argent (billets ou pieces) dans votre porte monnaie</p>";
					}
				}
			}
		}

		if ( !isset($_SESSION["EUR"])) {
			$money = MoneyFactory::getDefaultFactory()->createMoney(0, 0, "EUR");
			$_SESSION["EUR"] = serialize($money);
		}

		echo "etat de votre porte monnaie :"; echo"<br/>";
		$money = unserialize($_SESSION["EUR"]);
		echo $money->getValueNote() . " EUR en billets et " . $money->getValuePiece() . " EUR en pieces";
		?>

		<hr width='20%' align='left'/>
		<form action='index.php' method='post' id='form'>
		<table>
			<tr>
				<td>Valeur</td>
				<td>Devise</td>
				<td>Type</td>
			</tr>
			<tr>
				<td><input type='text' id='v1' name='v1'/></td>
				<td>
					<input type="text" id="devise" name="devise">
				</td>
				<td>
					<select name="type" id="type">
						<option value="valueNote">billets</option>
						<option value="valuePiece">pieces</option>
					</select>
				</td>
			  <td><input type='submit' id='add' name='add' value='ajouter'/></td>
			  <td><input type="submit" id="sub" name="sub" value='enlever'/></td>	
			</tr>
		</table>
		</form>
	</body>
</html>
